import Icon from '@/components/Icon'
import { RootState } from '@/types/store'
import { NavBar, Input, List } from 'antd-mobile'
import { useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import styles from './index.module.scss'
import io, { Socket } from 'socket.io-client'
import { getToken } from '@/utils/storage'

type ChatList = {type:'user'|'robot', text: string}[]
const Chat = () => {
  console.log('chat......')
  const user = useSelector((state: RootState) => state.profile.user)
  const history = useHistory()
  const [list, setList] = useState<ChatList>([{ type: 'user', text: '你好~' }, { type: 'robot', text: '你好！' }])
  const [text, setText] = useState('')

  const client = useRef<Socket|null>(null)

  useEffect(() => {
    client.current = io('http://toutiao.itheima.net', { query: { token: getToken().token }, transports: ['websocket'] })
    // 当和服务器建立连接成功，这个事件就会触发
    client.current.on('connect', () => {
      console.log('服务器建立连接成功')
    })

    // 接收服务器的消息
    client.current.on('message', (obj) => {
      console.log('服务器的数据是', obj)
      // 把收到的消息填充到list
      setList((list) => [...list, { type: 'robot', text: obj.msg }])
    })
  }, [])
  // 点击按钮，发消息
  const sendMessage = () => {
    console.log(client)
    if (text.trim() === '') {
      return
    }
    // 向服务器发消息
    if (client.current) {
      // 1. 发消息
      client.current.emit('message', { msg: text, timestamp: Date.now() })
      // 2. 追加到list
      setList([...list, { type: 'user', text }])
      // 3. 清空
      setText('')
    }
  }
  const refList = useRef<HTMLDivElement>(null)
  useEffect(() => {
    console.log('list变化了')
    // dom操作
    if (refList.current) {
      refList.current.scrollTop = refList.current?.scrollHeight
    }
  }, [list])
  return (
    <div className={styles.root}>
      {/* 顶部导航栏  go(-1) 就是后退 */}
      <NavBar className="fixed-header" onBack={() => history.go(-1)}>
        小智同学
      </NavBar>

      {/* 聊天记录列表 */}
      <div className="chat-list" ref={refList}>
          {
              list.map((it, idx) => {
                if (it.type === 'robot') {
                  /* 机器人的消息 */
                  return (<div key={idx} className="chat-item">
                    <Icon type="iconbtn_xiaozhitongxue" />
                    <div className="message">{it.text}</div>
                    </div>)
                } else {
                  /* 用户的消息 */
                  return (
                        <div key={idx} className="chat-item user">
                          <img src={user.photo} alt="" />
                          <div className="message">{it.text}</div>
                        </div>)
                }
              })
          }

      </div>

      {/* 底部消息输入框 */}
      <div className="input-footer">
        <List.Item
          className="login-code-extra"
          extra={<span className="code-extra" onClick={sendMessage}>发送</span>}>
          <Input className="no-border" value={text} onChange={(str) => setText(str)} placeholder="请描述您的问题" />
        </List.Item>

        <Icon type="iconbianji" />
      </div>
    </div>
  )
}

export default Chat
